//
//  PersonInfoAuthenVC.m
//  HxgProject
//
//  Created by hxg on 2018/3/7.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "CompanyAuthenVC.h"
#import "PersonInfoCell.h"

#import "UIViewController+HXExtension.h"

#import "RDVTabBarController.h"

#import "AuthenService.h"
#import "UIButton+Extention.h"
#import <IQKeyboardReturnKeyHandler.h>
#import "HxgTools.h"

#import "CompanyInfo.h"

@interface CompanyAuthenVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextFieldDelegate>
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
    
    // 文本输入框cell的默认高度
    float textFiledDefaultHeight;
}

@property (nonatomic, strong) UITableView *companyTableView;

// 配置数据源
@property (nonatomic, strong) NSMutableArray *companyDataSource;

// 提交按钮
@property (nonatomic, strong) UIButton *submitBtn;

@end

@implementation CompanyAuthenVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    textFiledDefaultHeight = 60;
    
    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    
    if (isCompanyAuthenSuc) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    } else {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    [super viewWillDisappear:animated];
}


- (void)setUpUI
{
    self.navigationItem.title = @"单位信息认证";
    self.view.backgroundColor = defaultViewBgColor;
    [self.view addSubview:self.companyTableView];
    
    [self.companyTableView registerClass:[PersonInfoCell class]
                 forCellReuseIdentifier:@"PersonCell"];
    [self.companyTableView makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }else{
            make.top.equalTo(self.view.mas_top);
        }
        make.left.equalTo(self.view.mas_left);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 60.0 * 5));
    }];
    
    [self.view addSubview:self.submitBtn];
    [_submitBtn setTitle:@"提交认证" forState:UIControlStateNormal];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kCompanyAuthenRes])
    {
        _submitBtn.userInteractionEnabled = NO;//交互关闭
        _submitBtn.alpha = 0.4;//透明度
    } else {
        _submitBtn.userInteractionEnabled = YES;//交互打开
        _submitBtn.alpha = 1;//透明度
    }
    
    [_submitBtn makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.companyTableView.mas_bottom).offset(5.0f);
        make.size.mas_equalTo(CGSizeMake(kScreen_Width /3.0f, 70.0f));
    }];
}

-(UITableView *)companyTableView
{
    if (!_companyTableView)
    {
        _companyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, kScreen_Width, kScreen_Height - 44.0f) style:UITableViewStyleGrouped];
        
        _companyTableView.delegate = self;
        _companyTableView.dataSource = self;
        _companyTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, KIphoneSize_Height(20.0f))];
        _companyTableView.tableFooterView = [[UIView alloc] init];
        _companyTableView.showsVerticalScrollIndicator = NO;
    }
    
    return _companyTableView;
}


#pragma mark - tableViewDelegate

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return 0;
    }
    
    return 0.01f;//section头部高度
}
//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return [[UIView alloc] init];
    }
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    static NSString *identifier = @"PersonCell";
    
    PersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell)
    {
        cell = [[PersonInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!isEmptyString(self.companyInfo.companyName)) {
        if (indexPath.row == 0) {
            cell.autherContentField.text = self.companyInfo.companyName;
        } else if (indexPath.row == 1) {
            cell.autherContentField.text = self.companyInfo.companyAddress;
        }else if (indexPath.row == 2) {
            cell.autherContentField.text = self.companyInfo.companyLeaderPhone;
        }
    }
    
    cell.autherContentField.delegate = self;
    cell.autherContentField.tag = indexPath.row;
    [cell.autherContentField addTarget:self
                                action:@selector(getInputVal:)
                      forControlEvents:UIControlEventEditingChanged];
    
    cell.autherNameLbl.text = [self.companyDataSource objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - ###### 根据需要设置cell ######
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 1 == indexPath.row ? textFiledDefaultHeight : 60.0f;
    
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 1)
    {
        return 1;
    }
    
    return self.companyDataSource.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - all Actions
- (void)getInputVal:(UITextField *)field
{
    switch (field.tag) {
        case 0:
            self.companyInfo.companyName = field.text;
            NSLog(@"self.personInfo.name==>%@ === %@",self.companyInfo.companyName,field.text);
            break;
        case 1:
            self.companyInfo.companyAddress = field.text;
            break;
        case 2:
            self.companyInfo.companyLeaderPhone = field.text;
            break;
        default:
            break;
    }
}

- (void)submitAction:(UIButton *)btn
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kCompanyAuthenRes])
    {
        [SVProgressHUD showErrorWithStatus:@"您已认证过,请勿重复提交!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    // 新增非空判断
    if (isEmptyString(self.companyInfo.companyName)
        || isEmptyString(self.companyInfo.companyAddress)
        || isEmptyString(self.companyInfo.companyLeaderPhone))
    {
        [SVProgressHUD showErrorWithStatus:@"内容不能为空!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在请求.."];
    __weak CompanyAuthenVC *weakSelf = self;
    AuthenService *authenService = [[AuthenService alloc] init];
    [authenService saveOrUpdateCompanyInfo:self.companyInfo
                              withCallBack:^(BOOL isSuccess) {
                                [SVProgressHUD dismiss];
                                if (isSuccess)
                                {
                                    [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                            forKey:kCompanyAuthenRes];
                                    [SVProgressHUD showSuccessWithStatus:@"操作成功!"];
                                    [weakSelf.navigationController popViewControllerAnimated:YES];
                                }
                                else
                                {
                                    [[NSUserDefaults standardUserDefaults] setBool:NO
                                                                            forKey:kCompanyAuthenRes];
                                    [SVProgressHUD showErrorWithStatus:@"操作失败!"];
                                }
                                  [SVProgressHUD dismissWithDelay:2.0f];
                            }];
}


-(NSMutableArray *)companyDataSource
{
    if (!_companyDataSource)
    {
        _companyDataSource = [[HxgTools sharedHxgTools] getProprotiesFormPlistFile:@"CompanyInfo"];
    }
    return _companyDataSource;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kCompanyAuthenRes])
    {
        return NO;
    }
    return YES;
}

#pragma mark - ###### getter、setter ######

- (UIButton *)submitBtn
{
    if (!_submitBtn)
    {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitBtn.layer.cornerRadius = 6.0f;
        [_submitBtn setBackgroundColor:kCommonBtnBgColor];
        [_submitBtn addTarget:self
                       action:@selector(submitAction:)
             forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitBtn;
}

- (CompanyInfo *)companyInfo
{
    if (!_companyInfo) {
        _companyInfo = [[CompanyInfo alloc] init];
    }
    return _companyInfo;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
